import {
  uploadImg
} from '../../api/editor'
import * as types from '../motations-type'
import Theme from '../../model/Theme'
import app from '../../libs/util/appConst'
import Element from '../../model/Element'
import Page from '../../model/Page'
import tool from '../../libs/tool'

export default {
  state: {
    editorElement: {}, // 正在编辑的元素
    editorPage: {
      elements: []
    }, // 正在编辑的页面
    themeList: [], // 用户所有主题列表
    editorTheme: {
      title: '',
      description: '',
      canvasHeight: 504
    }, // 正在编辑的主题
    picList: [], // 图片列表
    videoList: [] // 视频列表
  },
  getters: {
    editingElement: state => state.editorElement,
    editingTheme: state => state.editorTheme,
    editingPage: state => state.editorPage,
    editingPageElements: state => state.editorPage.elements
  },
  mutations: {
    [types.CREATE_THEME] (state, data) {
      state.themeList.push(data)
    },
    [types.SET_CUR_EDITOR_THEME] (state, data) {
      state.editorTheme = data
    },
    [types.SET_CUR_EDITOR_ELEMENT] (state, data) {
      state.editorElement = data
    },
    [types.ADD_PIC_ELEMENT] (state, data) {
      state.editorPage.elements.push(new Element(data))
    },
    [types.SET_BG_ELEMENT] (state, data) {
      let haveBG = false
      state.editorPage.elements.findIndex((value, index, arr) => {
        if (value.type === 'bg') {
          haveBG = true
          value.imgSrc = data.imgSrc
          value.width = data.width
          value.height = data.height
        }
      })
      if (!haveBG) {
        state.editorPage.elements.push(new Element(data))
      }
    },
    // 播放动画
    [types.PLAY_ANIMATE] (state) {
      let elements = state.editorPage.elements
      let editingElement = state.editorElement
      if (editingElement && editingElement.animatedName) {
        // 如存在有动画的选择元素
        editingElement.playing = true
      } else if (!editingElement) {
        // 不存在被选择的元素
        elements.forEach(v => {
          v.playing = true
        })
      }
    },
    // 停止播放动画
    [types.STOP_ANIMATE] (state, data) {
      if (data instanceof Array) {
        // 该页元素
        data.forEach(v => {
          v['playing'] = false
        })
      } else if (data instanceof Object) {
        // 单个元素
        data['playing'] = false
      } else {
        // 不传参情况
        state['editorPage']['elements'].forEach(v => {
          v['playing'] = false
        })
      }
    },
    [types.ADD_PAGE] (state, page) {
      state.editorTheme.pages.push(page)
    },
    [types.DELETE_PAGE] (state, data) {
      state.editorTheme.pages.findIndex((value, index, arr) => {
        if (value === data) {
          state.editorTheme.pages.splice(index, 1)
        }
      })
    },
    [types.SET_CUR_EDITOR_PAGE] (state, data) {
      state.editorPage = data
    },
    [types.GET_USER_THEME_LIST] (state, data) {
      state.themeList = data
    },
    [types.SET_CUR_EDITOR_THEME] (state, data) {
      state.editorTheme = data
    },
    [types.UPDATE_THEME_DES] (state, { title, description, canvasHeight }) {
      state.editorTheme.title = title
      state.editorTheme.description = description
      state.editorTheme.canvasHeight = canvasHeight
    },
    [types.DELETE_ELEMENT] (state, data) {
      state.editorPage.elements.findIndex((value, index, arr) => {
        if (value === data) {
          state.editorPage.elements.splice(index, 1)
          state.editorElement = null
        }
      })
    },
    [types.CREATE_THEME] (state, data) {
      state.themeList.push(data)
    },
    [types.ADD_THEME_SUCCESS] (state, data) {
      state.editorTheme._id = data._id
    },
    [types.UPDATE_THEME_SUCCESS] (state, data) {
    },
    [types.SAVE_PIC] (state, data) {
      state.editorElement.imgSrc = app.APP_MALL_API_URL + data.filePath
    },
    [types.GET_PAGE_THEMEID] (state, data) {
      state.editorPage = data
    },
    [types.CLEAN_BG] (state) {
      state.editorPage.elements.findIndex((value, index, arr) => {
        if (value && value.type === 'bg') {
          state.editorPage.elements.splice(index, 1)
        }
      })
    },
    [types.CLEAN_ELE] (state, ele) {
      state.editorPage.elements.splice(state.editorPage.elements.indexOf(ele), 1)
    },
    [types.FETCH_PIC_LIST] (state, picList) {
      state.picList = picList
    },
    [types.FETCH_VIDEO_LIST] (state, videoList) {
      state.videoList = videoList
    },
    [types.PUSH_PIC_LIST] (state, ele) {
      state.picList.push(ele)
    },
    [types.PUSH_VIDEO_LIST] (state, ele) {
      state.videoList.push(ele)
    },
    [types.CLEAN_PIC_LIST] (state) {
      state.picList = []
    },
    [types.SORTELEMENTS] (state, data) {
      let element = state.editorPage.elements[data.start]
      let end = parseInt(data.end)
      if (end !== -1) {
        state.editorPage.elements.splice(data.start, 1)
        if (end >= state.editorPage.elements.length) {
          state.editorPage.elements.push(element)
        } else {
          state.editorPage.elements.splice(end, 0, element)
        }
        state.editorPage.elements.map((value, index, arr) => {
          value.zindex = index + 1
        })
      }
    },
    [types.DELETE_THEME] (state, data) {
      state.themeList.findIndex((value, index, arr) => {
        if (value === data) {
          state.themeList.splice(index, 1)
        }
      })
    },
    [types.SORTELEMENTS_BY_ZINDEX] (state, data) {
      state.editorPage.elements.sort((a, b) => a['zindex'] - b['zindex'])
      state.editorPage.elements.forEach((v, i, arr) => {
        arr[i]['zindex'] = i + 1
      })
    }

  },
  actions: {
    /**
     * 保存页面数据
     */
    async saveTheme ({ commit }, theme) {
      if (theme && theme._id) {
        return Promise.resolve(api.updateTheme(theme).then((res) => {
          commit(types.UPDATE_THEME_SUCCESS, res)
        }))
      } else {
        return Promise.resolve(api.saveTheme(theme).then((res) => {
          commit(types.ADD_THEME_SUCCESS, res)
        }))
      }
    },

    async uploadFile ({ commit }, playload) {
      await uploadImg(playload)
    },

    /**
     * 获取用户所有场景主题
     * @param commit
     */
    async getUserThemeList ({ commit }, type) {
      api.getUserThemeList(type).then((res) => {
        commit(types.GET_USER_THEME_LIST, res)
      })
    },

    /**
     * 创建场景主题
     * @param commit
     */

    async createTheme ({ commit }, type) {
      var theme = new Theme({ type: type })
      commit(types.CREATE_THEME, theme)
      commit(types.SET_CUR_EDITOR_THEME, theme)
    },

    /**
     * 设置当前编辑的主题
     */
    async setEditorTheme ({ commit }, theme) {
      var newTheme = new Theme(theme)
      commit(types.SET_CUR_EDITOR_THEME, newTheme)
    },

    /**
     * 设置当前正在编辑的页面
     * @param commit
     * @param page
     */
    async setEditorPage ({ commit }, page) {
      commit(types.SET_CUR_EDITOR_PAGE, page)
    },

    /**
     * 给主题添加页面
     * @param commit
     */
    async addPage ({ commit }) {
      var page = new Page()
      commit(types.ADD_PAGE, page)
      commit(types.SET_CUR_EDITOR_PAGE, page)
    },

    /**
     * 添加页面元素
     */
    async addElement ({ commit, state }, data) {
      commit(types.ADD_PIC_ELEMENT, new Element(data))
      var list = state.editorPage.elements
      var lastIndex = list.length - 1
      list[lastIndex]['zindex'] = lastIndex ? list[lastIndex - 1]['zindex'] + 1 : 1
      commit(types.SET_CUR_EDITOR_ELEMENT, state.editorPage.elements[lastIndex])
    },

    /**
     * 添加背景图片
     */
    async addBGElement ({ commit }, data) {
      var element = new Element(data)
      commit(types.SET_BG_ELEMENT, element)
      commit(types.SET_CUR_EDITOR_ELEMENT, null)
    },

    /**
     * 保存图片
     * @param commit
     * @param data
     */
    async savePic ({ commit }, data) {
      commit(types.PUSH_PIC_LIST, data)
    },

    /**
     * 保存视频
     * @param commit
     * @param data
     */
    async saveVideo ({ commit }, data) {
      commit(types.PUSH_VIDEO_LIST, data)
    },
    /**
     * 清除背景
     * @param commit
     */
    async cleanBG ({ commit }) {
      commit(types.CLEAN_BG)
    },

    async cleanEle ({ commit }, ele) {
      commit(types.CLEAN_ELE, ele)
    },
    /**
     * 复制页面
     * @param commit
     */
    async copyPage ({ commit }, data) {
      var page = tools.vue2json(data)
      commit(types.ADD_PAGE, page)
    },

    /**
     * 删除页面
     * @param commit
     */
    async delPage ({ commit }, page) {
      commit(types.DELETE_PAGE, page)
    },

    async getPageByThemeId ({ dispatch, commit }, id) {
      api.getPageByThemeId(id).then((res) => {
        commit(types.SET_CUR_EDITOR_THEME, res)
        commit(types.SET_CUR_EDITOR_PAGE, res.pages[0])
      }).then(() => {
        dispatch('sortElementsByZindex')
      })
    },

    async setEditorElement ({ commit }, element) {
      commit(types.SET_CUR_EDITOR_ELEMENT, element)
    },

    // 删除元素
    async deleteElement ({ commit }, element) {
      commit(types.DELETE_ELEMENT, element)
    },

    async deleteSelectedElement ({ commit, state }) {
      commit(types.DELETE_ELEMENT, state.editorElement)
    },

    async playAnimate ({ state, commit, getters }) {
      commit(types.PLAY_ANIMATE)
      let target = getters['editingElement'] || getters['editingPageElements'] || null
      let time = 0
      if (target instanceof Array) {
        target.forEach(v => {
          time = v['animatedName'] && (v['duration'] + v['delay']) > time ? (v['duration'] + v['delay']) : time
        })
      } else if (target instanceof Object) {
        time = (target['duration'] + target['delay'])
      }
      setTimeout(() => {
        commit(types.STOP_ANIMATE, target)
      }, time * 1000)
    },

    async getPicListByThemeId ({ commit }, _id) {
      api.getPicListByThemeId(_id).then((res) => {
        commit(types.FETCH_PIC_LIST, res)
      })
    },
    async getVideoListByThemeId ({ commit }, _id) {
      api.getVideoListByThemeId(_id).then((res) => {
        commit(types.FETCH_VIDEO_LIST, res)
      })
    },

    async cleanPicList ({ commit }) {
      commit(types.CLEAN_PIC_LIST)
    },

    async sortElementsByZindex ({ commit }, location) {
      commit(types.SORTELEMENTS_BY_ZINDEX, location)
    },

    async deleteTheme ({ commit }, theme) {
      return Promise.resolve(api.delTheme(theme).then((res) => {
        commit(types.DELETE_THEME, theme)
      }))
    }
  }
}
